package com.practice.java8.stream;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectorMain {

	public static void main(String[] args) {
		groupingBy();
		partitioningBy();
	}
	
	public static void groupingBy() {
		Map<Integer, List<Person>> personGroups = 
			Stream.generate(new PersonSupplier()).limit(100)
			.collect(Collectors.groupingBy(Person::getAge));
		Iterator<Entry<Integer, List<Person>>> it = personGroups.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<Integer, List<Person>> persons = 
				(Map.Entry<Integer, List<Person>>) it.next();
			System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());
		}
	}
	
	public static void partitioningBy() {
		Map<Boolean, List<Person>> children = 
			Stream.generate(new PersonSupplier()).limit(100)
			.collect(Collectors.partitioningBy(p -> p.getAge() < 18));
		System.out.println("Children number: " + children.get(true).size());
		System.out.println("Adult number: " + children.get(false).size());
	}
	
	private static class PersonSupplier implements Supplier<Person> {

		private int index = 0;

		private Random random = new Random();

		@Override
		public Person get() {
			return new Person(index++, random.nextInt(100));
		}

	}

	private static class Person {

		private Integer number;

		private Integer age;

		public Person(Integer number, Integer age) {
			this.number = number;
			this.age = age;
			System.out.println(number + ", " + age);
		}

		public Integer getNumber() {
			return number;
		}

		public Integer getAge() {
			return age;
		}

	}

}
